<template>
  <div>
    <!-- 面包屑组件 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <!-- 需要用native属性 -->
      <el-breadcrumb-item :to="{ path: '/home' }" @click.native="returnHome"
        >首页</el-breadcrumb-item
      >
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 前置警告提示框 -->
      <el-alert
        title="注意！只能对最后一级的商品设置参数"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
      <el-row class="goods_opts">
        <el-col>
          <span>商品分类列表：</span>
          <!-- 级联选择器显示分类 -->
          <el-cascader
            v-model="paramsSelectKeys"
            :options="catesList"
            :props="paramsProps"
            @change="handleCascaderChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab栏切换效果  many表示动态 only表示静态 -->
      <el-tabs v-model="activeName" @tab-click="handleTabsClick">
        <el-tab-pane label="动态参数" name="many">
          <!-- 当级联选择未选择时，按钮禁用 -->
          <el-button
            type="primary"
            :disabled="isBtnEnabled"
            size="mini"
            @click="addDialogVisible = true"
            >添加参数</el-button
          >
          <!-- 动态参数详情 -->
          <el-table border stripe :data="manyTableData">
            <!-- 扩展列与序列列 -->
            <el-table-column type="expand">
              <template v-slot="{ row }">
                <el-tag
                  closable
                  v-for="(att, i) in row.attr_vals"
                  @close="handleTagClose(i, row)"
                  :key="i"
                  >{{ att }}</el-tag
                >
                <!-- 添加的tag -->
                <el-input
                  class="input-new-tag"
                  v-if="row.inputVisible"
                  v-model="row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(row)"
                  @blur="handleInputConfirm(row)"
                  autofocus
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <!-- 操作模板  -->
              <template v-slot="{ row }">
                <!-- 修改按钮 -->
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(row)"
                  >编辑</el-button
                >
                <!-- 删除按钮 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteCateById(row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            :disabled="isBtnEnabled"
            size="mini"
            @click="editDialogVisible = true"
            >添加属性</el-button
          >
          <!-- 静态参数详情 -->
          <el-table border stripe :data="onlyTableData">
            <!-- 扩展列与序列列 -->
            <el-table-column type="expand">
              <template v-slot="{ row }">
                <el-tag
                  closable
                  v-for="(att, i) in row.attr_vals"
                  :key="i"
                  @close="handleTagClose(i, row)"
                  >{{ att }}</el-tag
                >
                <!-- 添加的tag -->
                <el-input
                  class="input-new-tag"
                  v-if="row.inputVisible"
                  v-model="row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(row)"
                  @blur="handleInputConfirm(row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <!-- 操作模板  -->
              <template v-slot="{ row }">
                <!-- 修改按钮 -->
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(row)"
                  >编辑</el-button
                >
                <!-- 删除按钮 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteCateById(row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table></el-tab-pane
        >
      </el-tabs>
    </el-card>

    <!-- 添加的会话框 -->
    <el-dialog
      :title="'添加' + titelText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form
        :model="addRuleForm"
        :rules="addRules"
        ref="addFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="titelText" prop="attr_name">
          <el-input v-model="addRuleForm.attr_name"></el-input> </el-form-item
      ></el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>
    <!--edit的会话框 -->
    <el-dialog
      :title="'添加' + titelText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editRuleForm"
        :rules="editRules"
        ref="editFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="titelText" prop="attr_name">
          <el-input v-model="editRuleForm.attr_name"></el-input> </el-form-item
      ></el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Params',
  data () {
    return {
      catesList: [],
      // 级联选择器配置
      paramsProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      // 当前被选中的
      paramsSelectKeys: [],
      // tab 所属 属性
      activeName: 'many',
      // 动态静态两个数据
      manyTableData: [],
      onlyTableData: [],
      // 添加会话框数据
      addDialogVisible: false,
      addRuleForm: {
        attr_name: ''
      },
      addRules: {
        attr_name: [{
          required: true, message: '分类名称不能为空！', trigger: 'blur'
        }, { min: 2, max: 8, message: '参数名在2-8个字符！', trigger: 'blur' }]
      },
      // 编辑会话框数据
      editDialogVisible: false,
      editRuleForm: {
        attr_name: '',
        attrId: 0
      },
      editRules: {
        attr_name: [{
          required: true, message: '分类名称不能为空！', trigger: 'blur'
        }, { min: 2, max: 8, message: '参数名在2-8个字符！', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 依然是点击首页的优化
    returnHome () {
      this.$bus.$emit('changePath')
    },

    // 获取分类列表
    async getCatesList () {
      // 不传递参数，默认所有
      const { data: res } = await this.$https.get('categories')
      if (res.meta.status === 200) {
        this.catesList = res.data
      } else this.$message.error('商品分类信息获取失败！请重新加载')
    },
    // 级联选择器变化
    handleCascaderChange () {
      if (this.paramsSelectKeys.length === 3) { this.getCateParams() } else {
        // 当选择完三级别后，选择其他需要清空表格
        this.onlyTableData = []
        this.manyTableData = []
      }
    },
    // tabs点击处理
    handleTabsClick () {
      this.getCateParams()
    },
    // 获取参数
    async getCateParams () {
      if (this.paramsSelectKeys.length === 3) {
        const { data: res } = await this.$https.get(`categories/${this.cateId}/attributes`, {
          params: {
            sel: this.activeName
          }
        })
        if (res.meta.status === 200) {
          if (this.activeName === 'many') {
            // 先遍历再修改！
            // 拿到数据之后将具体参数的属性的内容做成数组
            // 但是要解决为空时仍然会有一个分隔出来，所以当为空串的时候直接返回一个空数组
            res.data.forEach(element => {
              element.attr_vals = element.attr_vals ? element.attr_vals.split(' ') : []
              // 解决公用一个input tag时会复用的问题
              element.inputVisible = false
              element.inputValue = ''
            })
            this.manyTableData = res.data
          } else {
            // 先遍历再修改！
            res.data.forEach(element => {
              element.attr_vals = element.attr_vals ? element.attr_vals.split(' ') : []
              // 解决公用一个input tag时会复用的问题
              element.inputVisible = false
              element.inputValue = ''
            })
            this.onlyTableData = res.data
          }
        } else return this.$message.error('获取参数失败！')
      }
    },
    // 关闭会话重置
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    addCate () {
      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$https.post(`categories/${this.cateId}/attributes`, {
            attr_name: this.addRuleForm.attr_name,
            attr_sel: this.activeName
          })
          if (res.meta.status === 201) {
            this.addDialogVisible = false
            this.getCateParams()
            this.$message.success('添加成功！')
          } else return this.$message.error('添加失败！')
        }
      })
    },
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    editCate () {
      // 预验证
      this.$refs.editFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$https.put(`categories/${this.cateId}/attributes/${this.editRuleForm.attrId}`, {
            attr_name: this.editRuleForm.attr_name,
            attr_sel: this.activeName
          })
          if (res.meta.status === 200) {
            this.editDialogVisible = false
            this.getCateParams()
            this.$message.success('修改成功！')
          } else return this.$message.error('修改失败！')
        }
      })
    },
    showEditDialog (cate) {
      this.editRuleForm.attrId = cate.attr_id
      this.editRuleForm.attr_name = cate.attr_name
      this.editDialogVisible = true
      console.log(cate)
    },
    // 删除属性会话框
    async deleteCateById (id) {
      // 返回的是一个promise对象 确定返回confirm 否则返回cancel字符串
      const result = await this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)
      // 发送删除请求 并刷新列表
      if (result === 'confirm') {
        const { data: res } = await this.$https.delete(`categories/${this.cateId}/attributes/` + id)
        if (res.meta.status === 200) {
          this.$message.success('删除成功！')
          this.getCateParams()
        } else this.$message.error('删除失败！')
        console.log(res)
      }
    },
    // 添加tag的处理事件
    async handleInputConfirm (row) {
      if (row.inputValue.trim() !== '') {
        // 添加操作 直接添加到对应数据的数组
        // 先添加再put
        row.attr_vals.push(row.inputValue)
        row.inputValue = ''
        // 发送请求修改数据库数据
        const { data: res } = await this.$https.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        })
        if (res.meta.status !== 200) {
          // 失败了就不再修改
          return this.$message.error('添加失败！')
        }
        this.$message.success('添加成功！')
      } else {
        // 解决残留问题
        row.inputValue = ''
      }
      row.inputVisible = false
    },
    // 显示添加tag的输入框
    showInput (row) {
      row.inputVisible = true
      // 因为这个时候修改完还没有刷新dom，故调用这个方法
      this.$nextTick(function () {
        this.$refs.saveTagInput.focus()
      })
    },
    // tag的删除事件
    async handleTagClose (i, row) {
      row.attr_vals.splice(i, 1)
      const { data: res } = await this.$https.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) {
        // 失败了就不再修改
        return this.$message.error('删除失败！')
      }
    }
  },
  computed: {
    isBtnEnabled () {
      if (this.paramsSelectKeys.length !== 3) { return true }
      return false
    },
    cateId () {
      if (this.paramsSelectKeys.length === 3) { return this.paramsSelectKeys[2] } else return null
    },
    titelText () {
      if (this.activeName === 'many') { return '动态参数' }
      return '静态参数'
    }
  },
  created () {
    this.getCatesList()
  }
}
</script>

<style scoped>
.goods_opts {
  margin: 15px 0;
}
.el-tag {
  margin: 8px;
}
.input-new-tag {
  width: 100px;
}
</style>
